package com.example.music.activity

import Utils.fadeout
import Utils.loadUrl
import android.content.Intent
import androidx.lifecycle.lifecycleScope
import com.example.lib_common_ui.base.BaseActivity
import com.example.lib_leancloud.LeanCloudManager
import com.example.music.databinding.ActivityAdvertisementBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AdvertisementActivity : BaseActivity<ActivityAdvertisementBinding>() {
    private var time = 2
    private lateinit var timeJob: Job
    override fun initUI() {
        LeanCloudManager.instance.loadAllMusic()
        LeanCloudManager.instance.loadCharts()
        val startTime = System.currentTimeMillis()
        LeanCloudManager.instance.loadAdv { manager, result ->

            manager.getRandomAdv().also { adv ->

                mBinding.ivAdv.loadUrl(adv.image)
                val endTime = System.currentTimeMillis()
                if (endTime - startTime < 2000) {
                    lifecycleScope.launch {
                        delay(1000 - (endTime - startTime))
                        showAdvertisement()
                    }
                } else {
                    showAdvertisement()
                }

            }
        }
    }

    private fun showAdvertisement() {
        hide()

        timeJob = lifecycleScope.launch(Dispatchers.IO) {
            while (true) {
                delay(1000)
                time--
                withContext(Dispatchers.Main) {
                    mBinding.time.text = time.toString()
                }
                if (time == 0) {
                    goToMainActivity()
                    timeJob.cancel(null)
                    break
                }
            }
        }
    }

    private fun goToMainActivity() {
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }

    private fun hide() {
        mBinding.back.fadeout()
    }
}